<template>
  <view class="container">
    <view class="address-list">
      <view 
        class="address-item" 
        v-for="(item, index) in addressList" 
        :key="index"
      >
        <view class="address-info" @click="selectAddress(item)">
          <view class="address-header">
            <text class="contact-name">{{ item.name }}</text>
            <text class="contact-phone">{{ item.tel }}</text>
          </view>
          <view class="address-detail">
            {{ item.address }}
          </view>
          <view v-if="item.default === '1'" class="default-tag">默认</view>
        </view>
        <view class="address-actions">
          <uni-icons type="compose" size="24" color="#ff0000" @click.stop="editAddress(item)"></uni-icons>
          <uni-icons type="closeempty" size="24" color="#ff0000" @click.stop="deleteAddress(item)"></uni-icons>
        </view>
      </view>
      
      <view class="empty-address" v-if="addressList.length === 0">
        <uni-icons type="location-filled" size="48" color="#ccc"></uni-icons>
        <text class="empty-text">暂无收货地址</text>
      </view>
    </view>
    
    <view class="add-address-btn" @click="addAddress">
      <uni-icons type="plusempty" size="20" color="#fff"></uni-icons>
      <text class="btn-text">新增地址</text>
    </view>
  </view>
</template>

<script>
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import { addressApi } from '@/api/indexAPI.js';

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      addressList: [],
      selectMode: false // 是否为选择模式
    };
  },
  onLoad(options) {
    // 判断是否为选择地址模式
    if (options && options.selectMode === 'true') {
      this.selectMode = true;
    }
    this.loadAddressList();
  },
  onShow() {
    // 页面显示时重新加载地址列表
    this.loadAddressList();
  },
  methods: {
    loadAddressList() {
      const userId = uni.getStorageSync('userId') || '';
      
      addressApi.getAddressList({
        uid: userId
      }).then(res => {
        console.log('获取地址列表成功:', res);
        if (res.code === 1) {
          this.addressList = res.data || [];
          console.log('地址列表数据:', this.addressList);
        } else {
          console.error("获取地址列表失败:", res);
          // 不提示获取失败，而是让用户添加地址
          this.addressList = [];
        }
      }).catch(err => {
        console.error("请求地址接口失败:", err);
        // 不提示网络错误，而是让用户添加地址
        this.addressList = [];
      });
    },
    
    selectAddress(address) {
      if (this.selectMode) {
        // 在选择模式下，将选中的地址存储到本地缓存并返回上一页
        uni.setStorageSync('selectedAddress', address);
        uni.navigateBack();
      } else {
        // 非选择模式下显示提示信息
        uni.showToast({
          title: '选择了地址: ' + address.name,
          icon: 'none'
        });
      }
    },
    
    editAddress(address) {
      // 跳转到编辑页面，并传递地址信息
      uni.navigateTo({
        url: '/pages/editlocal/editlocal?address=' + encodeURIComponent(JSON.stringify(address))
      });
    },
    
    deleteAddress(address) {
      console.log('准备删除地址:', address);
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个收货地址吗？',
        success: (res) => {
          if (res.confirm) {
            const userId = uni.getStorageSync('userId') || '';
            
            console.log('发送删除请求，地址ID:', address.id);
            addressApi.deleteAddress({
              id: address.id
            }).then(res => {
              console.log('删除地址响应:', res);
              if (res.code === 1) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新加载地址列表
                this.loadAddressList();
                
                // 如果是在选择模式下，通知支付页面刷新地址信息
                if (this.selectMode) {
                  uni.setStorageSync('addressUpdated', true);
                }
              } else {
                uni.showToast({
                  title: '删除失败: ' + (res.msg || ''),
                  icon: 'none'
                });
              }
            }).catch(err => {
              console.error("删除地址失败:", err);
              uni.showToast({
                title: '网络错误',
                icon: 'none'
              });
            });
          }
        }
      });
    },
    
    addAddress() {
      uni.navigateTo({
        url: '/pages/addlocal/addlocal'
      });
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.address-list {
  padding: 20rpx;
}

.address-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.contact-name {
  font-size: 32rpx;
  color: #333;
  margin-right: 20rpx;
}

.contact-phone {
  font-size: 28rpx;
  color: #333;
}

.address-detail {
  font-size: 26rpx;
  color: #999;
  line-height: 1.4;
}

.address-actions {
  width: 10%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  margin-left: 20rpx;
  margin-right: 26rpx;
}

.default-tag {
  display: inline-block;
  background-color: #ff0000;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 10rpx;
  border-radius: 4rpx;
  margin-top: 10rpx;
}

.empty-address {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  display: block;
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.add-address-btn {
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 600rpx;
  height: 80rpx;
  background-color: #ff0000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  color: #fff;
  font-size: 32rpx;
  margin-left: 10rpx;
}
</style>